package com.zhj.rpc06;

import com.zhj.common.entity.User;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author zhj
 */
public class Server {

    private static boolean runing = true;

    public static void main(String[] args) throws Exception {
        ServerSocket ss = new ServerSocket(8888);
        while (runing) {
            Socket s = ss.accept();
            process(s);
            s.close();
        }
        ss.close();
    }

    /**
     * 处理过程
     * @param s
     * @throws Exception
     */
    private static void process(Socket s) throws Exception {
        InputStream in = s.getInputStream();
        ObjectInputStream ois = new ObjectInputStream(in);
        OutputStream out = s.getOutputStream();

        String clazzName = ois.readUTF();
        String methodName = ois.readUTF();
        Class[] parameterTypes = (Class[]) ois.readObject();
        Object[] args = (Object[]) ois.readObject();

        Class clazz = null;
        // 从服务注册表找到具体的类 spring注入
        clazz = UserServiceImpl.class;

        Method method = clazz.getMethod(methodName, parameterTypes);
        Object o = (Object) method.invoke(clazz.newInstance(), args);

        ObjectOutputStream oos = new ObjectOutputStream(out);
        oos.writeObject(o);
        oos.flush();
    }

}
